﻿using AnlianCommon.Common.Domains.SheepFarmHouse;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using AnlianCommon.Enum;
using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AnlianCommon.API.Commands.Cottages
{
    public class CottageDeleteHander: IRequestHandler<CottageDeleteCommand, Result>
    {
        private readonly IMapper _mapper;
        private readonly IBaseRepository<Cottage> _cottageRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="personnelRepository"></param>
        /// <param name="mapper"></param>
        public CottageDeleteHander(IBaseRepository<Cottage> _cottageRepository, IMapper mapper)
        {
            this._cottageRepository = _cottageRepository;
            this._mapper = mapper;
        }

        /// <summary>
        /// 栋舍删除命令处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(CottageDeleteCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Deleted };
            try
            {
                var role = await(await _cottageRepository.GetAll()).Where(c => c.CottageId == request.CottageId).FirstOrDefaultAsync();
                if (role != null)
                {
                    role.IsDeleted = true;
                    role.DeletedOwnerId = "张三";
                    role.DeletedTime = DateTime.Now;
                    var res = await _cottageRepository.Update(role);
                    if (res > 0)
                    {
                        result.Code = (int)CommonErrorCode.Success;
                        result.Msg = "删除成功";
                    }
                    else
                    {
                        result.Code = (int)CommonErrorCode.Deleted;
                        result.Msg = "删除失败";
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
